package com.hanhanxiaochong.zhongxiangchuanmei.view.order.act;

import android.Manifest;
import android.content.Context;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.net.Uri;
import android.support.v4.app.ActivityCompat;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.hanhanxiaochong.zhongxiangchuanmei.R;
import com.hanhanxiaochong.zhongxiangchuanmei.alipay.Alipay;
import com.hanhanxiaochong.zhongxiangchuanmei.bean.OrderBean;
import com.hanhanxiaochong.zhongxiangchuanmei.bean.OrderGoodDetailBean;
import com.hanhanxiaochong.zhongxiangchuanmei.bean.OrderProjectDetailBean;
import com.hanhanxiaochong.zhongxiangchuanmei.bean.WXPayBean;
import com.hanhanxiaochong.zhongxiangchuanmei.presenter.OrderDetailPresenter;
import com.hanhanxiaochong.zhongxiangchuanmei.util.MessageEvent;
import com.hanhanxiaochong.zhongxiangchuanmei.util.ResourcesUtils;
import com.hanhanxiaochong.zhongxiangchuanmei.util.RxTimerUtil;
import com.hanhanxiaochong.zhongxiangchuanmei.util.SharedPreferencesUtil;
import com.hanhanxiaochong.zhongxiangchuanmei.util.ToastUtils;
import com.hanhanxiaochong.zhongxiangchuanmei.util.glide.GlideImgManager;
import com.hanhanxiaochong.zhongxiangchuanmei.view.base.BaseActivity;
import com.hanhanxiaochong.zhongxiangchuanmei.view.home.act.AppointmentSuccessActivity;
import com.hanhanxiaochong.zhongxiangchuanmei.view.home.act.ShopMapActivity;
import com.hanhanxiaochong.zhongxiangchuanmei.view.iview.IOrderDetailView;
import com.hanhanxiaochong.zhongxiangchuanmei.view.shop.act.PayDetailActivity;
import com.hanhanxiaochong.zhongxiangchuanmei.widget.checkbox.SmoothCheckBox;
import com.hanhanxiaochong.zhongxiangchuanmei.wxapi.WXPayUtils;
import com.wzgiceman.rxretrofitlibrary.retrofit_rx.http.RetrofitSource;
import com.wzgiceman.rxretrofitlibrary.retrofit_rx.utils.TimeUtils;

import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;

import butterknife.BindView;
import butterknife.OnClick;
import de.greenrobot.event.EventBus;
import de.greenrobot.event.Subscribe;
import de.greenrobot.event.ThreadMode;

/**
 * Author : 贾桐
 * E-mail : 653773284@qq.com
 * Time   : 2018/5/2.
 * Desc   : 订单待支付act
 */

public class OrderWaitPayActivity extends BaseActivity<OrderDetailPresenter> implements IOrderDetailView {


    @BindView(R.id.txt_left)
    TextView txtLeft;
    @BindView(R.id.img_left)
    ImageView imgLeft;
    @BindView(R.id.ll_leftview)
    RelativeLayout llLeftview;
    @BindView(R.id.txt_title)
    TextView txtTitle;
    @BindView(R.id.txt_right)
    TextView txtRight;
    @BindView(R.id.img_right)
    ImageView imgRight;
    @BindView(R.id.ll_rightview)
    RelativeLayout llRightview;
    @BindView(R.id.view_bottomline)
    View viewBottomline;
    @BindView(R.id.rl_topview)
    RelativeLayout rlTopview;
    @BindView(R.id.txt_countdown)
    TextView txtCountdown;
    @BindView(R.id.ll_container)
    LinearLayout llContainer;
    @BindView(R.id.tv_order_num)
    TextView tvOrderNum;
    @BindView(R.id.tv_order_status)
    TextView tvOrderStatus;
    @BindView(R.id.tv_order_phone)
    TextView tvOrderPhone;
    @BindView(R.id.tv_order_time)
    TextView tvOrderTime;
    @BindView(R.id.tv_order_technician)
    TextView tvOrderTechnician;
    @BindView(R.id.tv_order_service_time)
    TextView tvOrderServiceTime;
    @BindView(R.id.tv_order_deliver_way)
    TextView tvOrderDeliverWay;
    @BindView(R.id.txt_money)
    TextView txtMoney;
    @BindView(R.id.cb_alipay)
    SmoothCheckBox cbAlipay;
    @BindView(R.id.cb_wechat)
    SmoothCheckBox cbWechat;
    @BindView(R.id.cb_bank)
    SmoothCheckBox cbBank;
    @BindView(R.id.txt_pay)
    TextView txtPay;
    @BindView(R.id.ll_alipay)
    LinearLayout llAlipay;
    @BindView(R.id.ll_wechat)
    LinearLayout llWechat;
    @BindView(R.id.ll_paypal)
    LinearLayout llPaypal;

    private String token;
    private OrderBean bean;
    //1:上门取货 2:快递发货
    private String deliver = "1";
    //商品id 用,隔开
    private StringBuilder p_id = new StringBuilder();
    //门店id多商品门店id,隔开
    private StringBuilder s_id = new StringBuilder();
    //商品数量用,隔开
    private StringBuilder p_num = new StringBuilder();
    //商品总金额
    private double totalPrice;
    //地址id,如果选择上门取货则为null
    private String address_id = "";
    //优惠券id
    private String coupon_id = "";
    //1:包邮;2到付 用,拼接
    private StringBuilder freight = new StringBuilder();
    //支付方式 1:微信;2:支付宝;3:网银;4:余额
    private String payment = "2";

    public static Intent createIntent(Context context, OrderBean bean) {
        Intent intent = new Intent(context, OrderWaitPayActivity.class);
        intent.putExtra("bean", bean);
        return intent;
    }

    @Override
    protected void initView() {
        setContentView(R.layout.activity_order_waitpay);
        EventBus.getDefault().register(this);
        token = SharedPreferencesUtil.getsInstances(this).getLoginInfo().getToken();
        Intent intent = getIntent();
        bean = (OrderBean) intent.getSerializableExtra("bean");
    }

    @Override
    protected void initPresenter() {
        mPresenter = new OrderDetailPresenter(this);
    }

    @Override
    protected void init() {
        setTopView();
        String order_num = bean.getOrder_num();
        String order_id = bean.getId();
        String type = bean.getType();
        long leftTime = System.currentTimeMillis() / 1000 - Long.parseLong(bean.getAdd_time());
        RxTimerUtil.interval(1, leftTime, new RxTimerUtil.IRxNext() {
            @Override
            public void doNext(long number) {
                SimpleDateFormat sdf = new SimpleDateFormat("hh:mm:ss");
                String time = sdf.format(new Date((leftTime - number) * 1000));
                Log.i("RxTimerUtil", "doNext: " + (leftTime - number));
                txtCountdown.setText(String.format(ResourcesUtils.getString(R.string.order_left_time), time));
            }

            @Override
            public void doComplete() {
                RxTimerUtil.cancel();
            }
        });

        //1项目2产品
        if (type.equals("1")) {
            mPresenter.getProjectInfo(token, order_id, order_num);
        } else {
            mPresenter.getGoodInfo(token, order_id, order_num);
        }

        cbAlipay.setChecked(true);
        //支付宝
        cbAlipay.setOnToggleClickListener(isChecked -> {
            if (isChecked) {
                payment = "2";
                cbWechat.setChecked(false);
                cbBank.setChecked(false);
            }
        });
        //微信
        cbWechat.setOnToggleClickListener(isChecked -> {
            if (isChecked) {
                payment = "1";
                cbAlipay.setChecked(false);
                cbBank.setChecked(false);
            }
        });
        //银联
        cbBank.setOnToggleClickListener(isChecked -> {
            if (isChecked) {
                payment = "3";
                cbWechat.setChecked(false);
                cbAlipay.setChecked(false);
            }
        });
    }

    private void setTopView() {
        imgLeft.setImageResource(R.mipmap.icon_left);
        txtTitle.setText("订单详情");
    }

    @OnClick({R.id.ll_leftview, R.id.txt_pay, R.id.ll_alipay, R.id.ll_wechat, R.id.ll_paypal})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.ll_leftview:
                finish();
                break;
            case R.id.txt_pay:
                mPresenter.getOrderNumber(token, deliver, s_id.toString(), String.valueOf(totalPrice), p_id.toString(),
                        p_num.toString(), address_id, coupon_id, freight.toString(), payment);
                break;
            case R.id.ll_alipay:
                if (!cbAlipay.isChecked()) {
                    payment = "2";
                    cbAlipay.setChecked(true);
                    cbWechat.setChecked(false);
                    cbBank.setChecked(false);
                }
                break;
            case R.id.ll_wechat:
                if (!cbWechat.isChecked()) {
                    payment = "1";
                    cbAlipay.setChecked(false);
                    cbWechat.setChecked(true);
                    cbBank.setChecked(false);
                }
                break;
            case R.id.ll_paypal:
                if (!cbBank.isChecked()) {
                    payment = "3";
                    cbAlipay.setChecked(false);
                    cbWechat.setChecked(false);
                    cbBank.setChecked(true);
                }
                break;
        }
    }

    @Override
    public void setGoodInfo(OrderGoodDetailBean data) {
        txtMoney.setText(String.format(ResourcesUtils.getString(R.string.money), data.getPrice()));
        List<OrderGoodDetailBean.StoreBean> list = data.getStore();
        for (int i = 0; i < list.size(); i++) {
            OrderGoodDetailBean.StoreBean productBean = list.get(i);
            OrderGoodDetailBean.StoreBean.ListBean bean = productBean.getList();
            View view = LayoutInflater.from(mContext).inflate(R.layout.item_order_detail, llContainer, false);
            TextView shopName = view.findViewById(R.id.tv_shop_name);
            shopName.setText(productBean.getS_name());
            view.findViewById(R.id.img_phone).setOnClickListener(v -> {
                Intent intent = new Intent(Intent.ACTION_CALL);
                intent.setData(Uri.parse("tel:" + productBean.getPhone()));
                if (ActivityCompat.checkSelfPermission(this, Manifest.permission.CALL_PHONE) != PackageManager.PERMISSION_GRANTED) {
                    ToastUtils.showToast("拨打电话权限被禁止");
                    return;
                }
                startActivity(intent);
            });
            view.findViewById(R.id.img_location).setOnClickListener(v -> startActivity(ShopMapActivity.createIntent(this, Double.parseDouble(productBean.getLat()),
                    Double.parseDouble(productBean.getLng()), productBean.getS_name(), "")));
            LinearLayout childContainer = view.findViewById(R.id.ll_container);
            View childView = LayoutInflater.from(mContext).inflate(R.layout.item_order_good_or_project, childContainer, false);
            ImageView ivGoodPic = childView.findViewById(R.id.iv_good_pic);
            ImageView ivSelfSupport = childView.findViewById(R.id.iv_self_support);
            TextView tvGoodName = childView.findViewById(R.id.tv_good_name);
            TextView tvVipPrice = childView.findViewById(R.id.tv_vip_price);
            TextView tvNormalPrice = childView.findViewById(R.id.tv_normal_price);

            GlideImgManager.glideLoader(mContext, RetrofitSource.image_url + bean.getPic().split(",")[0], R.mipmap.img_error, R.mipmap.img_error, ivGoodPic);
            tvGoodName.setText(bean.getP_name());
            ivSelfSupport.setVisibility(bean.getSelf_support().equals("y") ? View.VISIBLE : View.GONE);
            tvVipPrice.setText(String.format(ResourcesUtils.getString(R.string.vip_good_price), bean.getPrice_vip()));
//                tvNormalPrice.setText(String.format(ResourcesUtils.getString(R.string.normal_good_price), bean.getPrice()));
            childContainer.addView(childView);
            if (i != 0 && productBean.getS_name().equals(list.get(i - 1).getS_name())) {
                view.findViewById(R.id.item_order_detail_header).setVisibility(View.GONE);
            }
            llContainer.addView(view);
        }

        tvOrderNum.setText(String.format(ResourcesUtils.getString(R.string.order_num), data.getOrder_num()));
        tvOrderPhone.setText(String.format(ResourcesUtils.getString(R.string.order_phone), SharedPreferencesUtil.getsInstances(this).getLoginInfo().getMobile()));
        tvOrderTime.setText(String.format(ResourcesUtils.getString(R.string.order_time), TimeUtils.getDateFromSeconds(data.getAdd_time())));
        tvOrderStatus.setText(String.format(ResourcesUtils.getString(R.string.order_status), "待支付"));
    }

    @Override
    public void setProjectInfo(OrderProjectDetailBean data) {
        View view = LayoutInflater.from(mContext).inflate(R.layout.item_order_good_or_project, llContainer, false);
        ImageView ivGoodPic = view.findViewById(R.id.iv_good_pic);
        ImageView ivSelfSupport = view.findViewById(R.id.iv_self_support);
        TextView tvGoodName = view.findViewById(R.id.tv_good_name);
        TextView tvVipPrice = view.findViewById(R.id.tv_vip_price);
        TextView tvNormalPrice = view.findViewById(R.id.tv_normal_price);
        TextView tvProjectFit = view.findViewById(R.id.tv_project_fit);
        TextView tvProjectTime = view.findViewById(R.id.tv_project_time);

        OrderBean.ProjectBean projectBean = bean.getProject().get(0);
        GlideImgManager.glideLoader(mContext, RetrofitSource.image_url + projectBean.getPic().split(",")[0], R.mipmap.img_error, R.mipmap.img_error, ivGoodPic);
        tvGoodName.setText(projectBean.getP_name());
        ivSelfSupport.setVisibility(projectBean.getSelf_support().equals("y") ? View.VISIBLE : View.GONE);
        tvVipPrice.setText(String.format(ResourcesUtils.getString(R.string.vip_good_price), projectBean.getPrice_vip()));
        tvNormalPrice.setText(String.format(ResourcesUtils.getString(R.string.normal_good_price), projectBean.getPrice()));
        tvProjectFit.setText(String.format(ResourcesUtils.getString(R.string.project_fit), projectBean.getSymptom_lists()));
        tvProjectTime.setText(String.format(ResourcesUtils.getString(R.string.project_time), projectBean.getTment_time()));

        llContainer.addView(view);

        tvOrderNum.setText(String.format(ResourcesUtils.getString(R.string.order_num), data.getOrder_num()));
        tvOrderPhone.setText(String.format(ResourcesUtils.getString(R.string.order_phone), SharedPreferencesUtil.getsInstances(this).getLoginInfo().getMobile()));
        tvOrderTime.setText(String.format(ResourcesUtils.getString(R.string.order_time), TimeUtils.getDateFromSeconds(data.getAdd_time())));
        tvOrderStatus.setText(String.format(ResourcesUtils.getString(R.string.order_status), "待支付"));
    }

    @Override
    public void hasDelivered(String data) {

    }

    @Override
    public void aliPay(String order_num) {
        new Alipay(this, order_num, new Alipay.AlipayResultCallBack() {
            @Override
            public void onSuccess() {
                startActivity(AppointmentSuccessActivity.createIntent(OrderWaitPayActivity.this, null));
            }

            @Override
            public void onDealing() {
                ToastUtils.showToast("支付处理中...");
            }

            @Override
            public void onError(int error_code) {
                switch (error_code) {
                    case Alipay.ERROR_RESULT:
                        ToastUtils.showToast("支付失败:支付结果解析错误");
                        break;

                    case Alipay.ERROR_NETWORK:
                        ToastUtils.showToast("支付失败:网络连接错误");
                        break;

                    case Alipay.ERROR_PAY:
                        ToastUtils.showToast("支付错误:支付码支付失败");
                        break;

                    default:
                        ToastUtils.showToast("支付错误");
                        break;
                }
            }

            @Override
            public void onCancel() {
                ToastUtils.showToast("支付取消");
            }
        }).doPay();
    }

    @Override
    public void wxPay(WXPayBean pay_param) {
        WXPayUtils.WXPayBuilder builder = new WXPayUtils.WXPayBuilder();
        builder.setAppId(pay_param.getAppid())
                .setPartnerId(pay_param.getPartnerid())
                .setPrepayId(pay_param.getPrepayid())
                .setPackageValue(pay_param.getPackageX())
                .setNonceStr(pay_param.getNoncestr())
                .setTimeStamp(pay_param.getTimestamp())
                .setSign(pay_param.getSign())
                .build().toWXPayNotSign(this, pay_param.getAppid());
    }

    @Override
    protected void onDestroy() {
        EventBus.getDefault().unregister(this);
        super.onDestroy();
    }

    @Subscribe(threadMode = ThreadMode.MainThread)
    public void handleEvent(MessageEvent event){
        if (event.getMessage().equals("pay_success")){
            finish();
        }
    }
}
